package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.MenuMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.service.IMenuService;
import com.xxxx.server.utils.GetAdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

	@Resource
	private MenuMapper menuMapper;
	@Resource
	private RedisTemplate<String,Object> redisTemplate;

	/**
	 * 根据当前用户获取菜单
	 *
	 * @return
	 */
	@Override
	public List<Menu> getMenusByAdminId() {
		//获取用户ID
		Integer id=GetAdminUtils.getAdmin().getId();
		//设置模板
		ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
		//从缓存中读取数据
		List<Menu> lists=(List<Menu>)valueOperations.get("menu_"+id);
		//如果缓存中无数据,则读取数据库存入redis
		if (CollectionUtils.isEmpty(lists)){
			lists=menuMapper.getMenusByAdminId(id);
			valueOperations.set("menu_"+id,lists);
		}
		return lists;
	}


	/**
	 * 查询所有菜单及对应角色
	 *
	 * @return
	 */
	@Override
	public List<Menu> getMenusWithRoles() {
		return menuMapper.getMenusWithRoles();
	}

	/**
	 * 获取所有菜单
	 * @return
	 */
	@Override
	public List<Menu> getAllMenus() {
		return menuMapper.selectAllList();
	}
}
